package com.cdream.basic.spring.lifecycle;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

/**
 * @author cdream
 * @date 2021/8/1
 */
// @Component
@Slf4j
public class PostProcessorExample implements InstantiationAwareBeanPostProcessor, PriorityOrdered {
    /**
     * bean创建之前执行，如果这里返回对象，则会跳过后面的步骤，除了postProcessAfterInitialization
     *
     * @param beanClass
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (StrUtil.containsIgnoreCase(beanName, "PostProcessor")) {
            log.error("before------------------beanName:{},beanClass:{}", beanName, beanClass);
        }
        return null;
    }

    /**
     * bean刚刚创建完成，还未设置属性，如果在这个方法中设置属性，可以返回false,跳过之后的属性填充
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (StrUtil.containsIgnoreCase(beanName, "PostProcessor")) {
            log.error("after------------------beanName:{},beanClass:{}", beanName, bean);
        }
        return true;
    }

    /**
     * 填充完属性，执行完aware后 和 initMethod之前调用，可对填充好属性的bean进行替换
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    /**
     * 填充完属性，执行完aware后 和 initMethod之前调用，可对填充好属性的bean进行替换
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
